<template>
  <div class="list-table">
    <div v-show="!menuKeyMark" class="area-header">
      <span class="area-header-title">{{ $t('项目划款') }}</span>
    </div>
    <el-form
      ref="queryForm"
      :model="queryParams"
      :inline="true"
    >
      <el-form-item :label="$t('申请标题')" prop="actTitle">
        <el-input v-model="queryParams.actTitle" :placeholder="$t('申请标题')" size="small" @keyup.enter.native="queryHandle" />
      </el-form-item>
      <el-form-item :label="$t('申请人')" prop="userName">
        <el-input v-model="queryParams.userName" :placeholder="$t('申请人')" />
      </el-form-item>
      <el-form-item :label="$t('划款类型')" prop="typeSubName">
        <el-select v-model="queryParams.typeSubName" :placeholder="$t('划款类型')">
          <el-option
            v-for="dict in typeMainOption"
            :key="dict.dictValue"
            :label="$t(dict.dictLabel)"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-show="menuKeyMark" :label="$t('是否已维护')" prop="whetherToMaintain">
        <dictSelect
          v-model="queryParams.whetherToMaintain"
          :clearable="true"
          dictionary="payment_maintenance"
          :placeholder="$t('请选择')"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
        <el-button v-has-permi="['deal:payment:view']" type="info" icon="el-icon-download" :disabled="showDownloadBtn" size="mini" @click="downloadFileAll">{{ $t('凭证下载') }}</el-button>
      </el-form-item>
    </el-form>

    <el-row v-if="!menuKeyMark" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['deal:payment:edit']" type="primary" icon="el-icon-plus" size="mini" @click="addHandle">{{ $t("新增") }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['deal:payment:export']" type="warning" icon="el-icon-download" size="mini" @click="exportHandle">{{ $t("导出") }}</el-button>
      </el-col>
    </el-row>

    <el-table
      ref="multipleTable"
      v-loading="loading"
      :element-loading-text="loadingText"
      tooltip-effect="darkTable"
      :data="DealPaymentList"
      class="nowrapTable"
      :show-summary="true"
      :summary-method="getSummaries"
      border
      @select-all="multiOperationAll"
      @select="multiOperation"
    >
      <el-table-column type="selection" width="40" :selectable="multiOperationChoice" />
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('申请标题')" align="center" prop="actTitle" :show-overflow-tooltip="true" min-width="250">
        <template slot-scope="scope">
          <span class="link-type" @click="updateHandle(scope.row)">{{ scope.row.actTitle }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="menuKeyMark" :label="$t('项目名称')" align="center" prop="dealName" min-width="100" :show-overflow-tooltip="true" />
      <el-table-column v-if="menuKeyMark" :label="$t('项目类型')" align="center" prop="dealType" min-width="100" :formatter="formatterDealType" />
      <el-table-column :label="$t('申请人')" align="center" prop="userName" :show-overflow-tooltip="true" min-width="90" />
      <el-table-column :label="$t('申请时间')" align="center" prop="applyTime" min-width="110">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('划款类型')" align="center" prop="typeSubName" :show-overflow-tooltip="true" min-width="100">
        <template slot-scope="scope">
          <span>{{ $t(scope.row.typeSubName) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('划款金额') + $t('金额单位')" header-align="center" align="right" prop="total" :show-overflow-tooltip="true" min-width="110">
        <template slot-scope="scope">
          <span class="money-text">{{ moneyFormat(scope.row.total, 'w') }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('实际划款金额') + $t('金额单位')" header-align="center" align="right" prop="total" :show-overflow-tooltip="true" width="130">
        <template slot-scope="scope">
          <span class="money-text">{{ sumTotal(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('币种')" align="center" prop="currency" :formatter="currencyFormat" :show-overflow-tooltip="true" min-width="90" />
      <el-table-column v-if="useProcess" fixed="right" :label="$t('审批状态')" align="center" min-width="120">
        <template slot-scope="scope">
          <ProcessStatus :status="scope.row.actStatus" :act-id="scope.row.actId" />
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" width="200px" class-name="small-padding fixed-width">
        <template slot="header">
          {{ $t('操作') }}
          <el-tooltip v-if="useProcess" v-hasPermi="['deal:payment:edit']" placement="top">
            <div slot="content">
              <span v-html="$t('审批结束后,对费用及划款时间的梳理, <br> 这里维护实际到账时间和金额.')" />
            </div>
            <i class="el-icon-question" />
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <div v-if="useProcess">
            <div v-if="!menuKeyMark">
              <ListBtn :bus-data="scope.row" :apply="scope.row.createBy.id" has-permi="deal:payment" style="display: block;margin-right:0;" :other-btn="scope.row.actStatus === 'W'" :data-table="'deal_payment'" />
              <div v-if="scope.row.actStatus === 'W'">
                <span slot="label">
                  <el-button
                    v-hasPermi="['deal:payment:maintain']"
                    size="small"
                    type="text"
                    icon="el-icon-edit"
                    @click="updatePayTimeBtn(scope.row)"
                  >{{ $t('维护划款信息') }}</el-button>
                  <!--                <el-button-->
                  <!--                  size="small"-->
                  <!--                  type="text"-->
                  <!--                  icon="el-icon-s-order"-->
                  <!--                  style="margin-left: 5px;"-->
                  <!--                  @click="dealPaymentDetailHandle(scope.row)"-->
                  <!--                >{{ $t('划款分摊明细') }}</el-button>-->
                </span>
              </div>
            </div>
            <div v-else>
              <div v-if="scope.row.actStatus === 'W'">
                <span slot="label">
                  <el-button
                    v-hasPermi="['deal:payment:maintain']"
                    size="small"
                    type="text"
                    icon="el-icon-edit"
                    @click="updatePayTimeBtn(scope.row)"
                  >{{ $t('维护划款信息') }}</el-button>
                  <!--                <el-button-->
                  <!--                  size="small"-->
                  <!--                  type="text"-->
                  <!--                  icon="el-icon-s-order"-->
                  <!--                  @click="dealPaymentDetailHandle(scope.row)"-->
                  <!--                >{{ $t('划款分摊明细') }}</el-button>-->
                </span>
              </div>
            </div>
          </div>
          <div v-else>
            <el-button
              v-hasPermi="['deal:payment:edit']"
              size="small"
              type="text"
              :disabled="!isEmpty(scope.row.actId)"
              icon="el-icon-edit"
              @click="updateHandle(scope.row)"
            >{{ $t('修改') }}</el-button>
            <el-button
              v-hasPermi="['deal:payment:remove']"
              size="small"
              type="text"
              :disabled="!isEmpty(scope.row.actId)"
              icon="el-icon-delete"
              @click="deleteHandle(scope.row)"
            >{{ $t('删除') }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 实际划款信息 -->
    <el-dialog
      :visible.sync="MaintainPaymentInforLoading"
      title="维护划款信息"
      :destroy-on-close="true"
      custom-class="dialogForm"
      append-to-body
      :close-on-click-modal="false"
      :lock-scroll="false"
    >
      <MaintainPaymentInfor ref="MaintainPaymentInfor" :act-title="MaintainPaymentInforTitle" @updatePayTimeSuccess="updatePayTimeSuccess" />
    </el-dialog>

    <OnlinePreview ref="OnlinePreview" />

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【项目划款】对话框 -->
    <el-dialog :title="$t(title)" :visible.sync="formOpen" width="70%" :close-on-click-modal="false" :destroy-on-close="true" append-to-body custom-class="dialogForm">
      <dealPaymentForm ref="dealPaymentForm" />
    </el-dialog>
    <!-- 项目划款明细列表 -->
    <el-dialog :title="$t(listTitle)" :visible.sync="listOpen" width="70%" :close-on-click-modal="false" append-to-body custom-class="dialogForm">
      <dealPaymentDetailList ref="dealPaymentDetailList" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listDealPayment,
  listDealPaymentByResult,
  delDealPayment,
  updatePayTime,
  getPaymentTimeFile,
  getDealPaymentSum,
  getDealPaymentSumByResult
} from '@/api/deal/payment/dealPayment'
  import dealPaymentForm from './dealPaymentForm.vue'
  import ProcessStatus from '@/components/Act/ProcessStatus'
  import MaintainPaymentInfor from '@/components/MaintainPaymentInfor'
  import { fdSubjectSelectByType } from '@/api/fd/config/fdSubjects'
  import dealPaymentDetailList from '@/views/deal/paymentDetail/dealPaymentDetailList'
  import { downLoadZip } from '@/utils/zipdownload.js'
import { getMenuProcess } from '@/api/act/process/wfMenuProcess'
  export default {
    components: {
      dealPaymentForm,
      ProcessStatus,
      MaintainPaymentInfor,
      dealPaymentDetailList
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 是否配置了流程
        useProcess: false,
        loadingText: '',
        // 总条数
        total: 0,
        // 【请填写功能名称】表格数据
        DealPaymentList: [],
        dealPaymentSum: [],
        // 弹出层标题
        title: '项目划款',
        listTitle: '',
        // 是否显示弹出层
        formOpen: false,
        listOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userName: '',
          dealId: this.$route.query.id,
          typeMainName: undefined,
          typeSubName: undefined,
          currency: undefined,
          whetherToMaintain: undefined,
          method: undefined,
          level: undefined,
          total: undefined,
          applyTime: undefined,
          payeeId: undefined,
          depositBank: undefined,
          accountTitle: undefined,
          bankNumber: undefined,
          addressReceiver: undefined,
          remark: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {},
        // 划款大类
        getFdSubjectList: [],
        // 划款大类
        typeMainOption: [],
        // 划款币种
        currencyOptions: [],
        MaintainPaymentInforTitle: '',
        MaintainPaymentInforLoading: false,
        menuKeyMark: undefined,
        dealTypeOption: [],
        showDownloadBtn: true,
        choiceDownloadRow: []
      }
    },
    created() {
      // 划款币种
      this.getDicts('currency').then(response => {
        this.currencyOptions = response.data
      })
      // 划款类型
      fdSubjectSelectByType('deal', 'oa_payment').then(response => {
        this.typeMainOption = response.data
      })
      this.getDicts('deal_type').then(response => {
        this.dealTypeOption = response.data
      })
      // 获取是否使用流程
      getMenuProcess('deal_payment').then(response => {
        this.useProcess = (response.data !== undefined && response.data !== null && response.data !== '')
      })
      this.getList()
    },
    methods: {
      currencyFormat(row) {
        return this.selectDictLabel(this.currencyOptions, row.currency)
      },
      formatterDealType(row) {
        return this.selectDictLabel(this.dealTypeOption, row.dealType)
      },
      // 合计实际划款金额
      sumTotal(row) {
        var money = 0
        if (row.investorList !== undefined && row.investorList !== null && row.investorList !== '') {
          row.investorList.forEach(item => {
            if (!isNaN(parseFloat(item.actualPaymentMoney))) {
              money += parseFloat(item.actualPaymentMoney)
            }
          })
        }
        return this.moneyFormat(money, 'w') === '0' ? '' : this.moneyFormat(money, 'w')
      },
      /** 查询列表 */
      getList() {
        this.menuKeyMark = this.$route.params.menuKeyMark
        this.loading = true
        if (this.menuKeyMark) {
          listDealPaymentByResult(this.queryParams).then(response => {
            getDealPaymentSumByResult(this.queryParams).then(res => {
              this.dealPaymentSum = res.data
            })
            this.DealPaymentList = response.rows
            this.total = response.total
            this.loading = false
          })
        } else {
          listDealPayment(this.queryParams).then(response => {
            getDealPaymentSum(this.queryParams).then(res => {
              this.dealPaymentSum = res.data
            })
            this.DealPaymentList = response.rows
            this.total = response.total
            this.loading = false
          })
        }
      },
      // 是否可选
      multiOperationChoice() {
        return true
      },
      // 全选操作
      multiOperationAll(selection) {
        this.showDownloadBtn = selection.length <= 0
        this.choiceDownloadRow = selection
      },
      // 单选操作
      multiOperation(selection, row) {
        this.showDownloadBtn = selection.length <= 0
        console.log('2', selection, row)
        this.choiceDownloadRow = selection
      },
      downloadFileAll() {
        this.loading = true
        var paymentIds = []
        this.choiceDownloadRow.forEach(item => {
          paymentIds.push(item.id)
        })
        // 后台开始打包下载
        getPaymentTimeFile(paymentIds.join(',')).then(response => {
          if (response.data !== null && response.data !== '') {
            console.log(response)
            downLoadZip('/file/fileBase/common/downloadZip?fileId=' + response.data, this)
          } else {
            this.$message({
              message: this.$t('划款信息中不存在凭证!'),
              type: 'warning'
            })
            this.loading = false
          }
          setTimeout(() => {
            this.loading = false
          }, 3000)
        })
      },
      downloadOpenLoading() {
        this.loading = true
        this.loadingText = '0%'
      },
      downloadProgress(num) {
        this.loadingText = num + '%'
      },
      downloadCloseLoading() {
        this.loading = false
        this.loadingText = ''
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          userName: undefined,
          typeMainName: undefined,
          typeSubName: undefined,
          currency: undefined,
          method: undefined,
          level: undefined,
          total: undefined,
          applyTime: undefined,
          payeeId: undefined,
          depositBank: undefined,
          accountTitle: undefined,
          bankNumber: undefined,
          addressReceiver: undefined,
          payCompletionTime: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          delFlag: undefined,
          remark: undefined
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.queryHandle()
      },
      /** 新增按钮操作 */
      addHandle() {
        this.formOpen = true
        this.$nextTick(() => {
          this.$refs.dealPaymentForm.init(null)
        })
      },
      /** 修改按钮操作 */
      updateHandle(row) {
        this.formOpen = true
        this.$nextTick(() => {
          this.$refs.dealPaymentForm.init(row)
          this.$refs.dealPaymentForm.$refs.form.clearValidate()
        })
      },
      /** 项目划款明细 */
      dealPaymentDetailHandle(row) {
        this.listOpen = true
        this.listTitle = this.$t('划款分摊明细')
        this.$nextTick(() => {
          // 调用List页面的 dealPaymentDetailList 方法初始化数据
          this.$refs.dealPaymentDetailList.getDealPaymentDetail(row)
        })
      },
      /** 删除按钮操作 */
      deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
          confirmButtonText: this.$t('确定'),
          cancelButtonText: this.$t('取消'),
          type: 'warning'
        })
          .then(function() {
            return delDealPayment(row.id)
          })
          .then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
          })
          .catch(function() {})
      },
      // 划款时间维护 : 按钮获取数据
      updatePayTimeBtn(row) {
        this.MaintainPaymentInforLoading = true
        this.MaintainPaymentInforTitle = row.actTitle + ' (' + this.formatCurrency(row.currency) + ')'
        this.$nextTick(() => {
          this.$refs.MaintainPaymentInfor.parentCurrency = row.currency
          this.$refs.MaintainPaymentInfor.init(row, 'deal_payment')
        })
      },
      formatCurrency(val) {
        const currency = this.currencyOptions.find(obj => obj.dictValue === val)
        if (currency) {
          return currency.dictLabel
        }
        return val
      },
      // 划款时间维护 : 保存到后台
      updatePayTimeSuccess(data, callback) {
        console.log(data)
        updatePayTime(data).then(respones => {
          if (respones.code === 200) {
            callback(true)
            this.msgSuccess('操作成功!')
            this.getList()
            this.MaintainPaymentInforLoading = false
          } else {
            callback(false)
            this.msgSuccess(this.$t('维护失败'))
          }
        })
      },
      /** 导出按钮操作 */
      exportHandle() {
        this.downLoadExcel('/payment/dealPayment/export', this.queryParams)
      },
      // 合计
      getSummaries(param) {
        const { columns } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计'
          } else if (index === 6) {
            sums[index] = this.moneyFormat(this.dealPaymentSum.total, 'w')
          } else if (index === 7) {
            sums[index] = this.moneyFormat(this.dealPaymentSum.payCompletionMoney, 'w')
          } else {
            sums[index] = ''
          }
        })
        return sums
      }
    }
  }
</script>
